<template>
  <div class="gk-table">
    <div class="filter-box">
      <!-- 院校筛选 -->
      <div class="filter-box-item" @click="showDialog(0)">
        <span
          :class="checkValid(filterList[0].name) ? 'content-active' : 'content'"
          >{{ filterList[0].name }}</span
        >
        <img :src="arrowDown" class="arrow-down" alt="" />

        <CollegeFeatureTypeDialog
          ref="collegeDialogRef"
          v-show="showCollegeDialog"
          @confirm="handleConfirmCollege"
        />
      </div>
      <!-- 专业筛选 -->
      <div class="filter-box-item" @click="showDialog(1)">
        <span
          :class="checkValid(filterList[1].name) ? 'content-active' : 'content'"
          >{{ filterList[1].name }}</span
        >
        <img :src="arrowDown" class="arrow-down" alt="" />
        <MajorDialog
          ref="majorDialogRef"
          v-show="showMajorDialog"
          @confirmMajor="handleConfirmMajor"
          @confirmIndustry="handleConfirmIndustry"
        />
      </div>
      <!-- 推荐分数筛选 -->
      <div class="filter-box-item" @click="showDialog(2)">
        <span
          :class="checkValid(filterList[2].name) ? 'content-active' : 'content'"
          >{{ filterList[2].name }}</span
        >
        <span class="score-text">{{ currentScoreRangeName }} 分</span>
        <img :src="arrowDown" class="arrow-down" alt="" />
        <RecommendScoreDialog
          ref="recommendScoreDialogRef"
          :gradeInfo="gradeInfo"
          v-show="showRecommendScoreDialog"
          @confirm="handleConfirmScoreRange"
        />
      </div>
      <div class="search-box">
        <SearchCollege
          placeholder="搜索你的意向院校"
          search-type="college"
          @select="handleSelectCollege"
          @clear="handleClear('college')"
          ref="searchCollegeRef"
        />
      </div>
    </div>
    <div class="table-contain">
      <div class="table-header">
        <div
          :class="['header-item', 'item' + index]"
          v-for="(item, index) in headerList"
          :key="index"
        >
          {{ item.label }}
        </div>
      </div>
      <div class="table-list" @scroll="handleScroll" ref="scrollContainer">
        <template v-if="schoolList.length > 0">
          <div
            class="table-item"
            v-for="(item, index) in schoolList"
            :key="index"
          >
            <div class="father-level" v-if="item.collegeInfo">
              <div class="first-column">
                <div
                  class="label match-rate-bg"
                  v-if="item.matchRate"
                  :class="[
                    item.matchRate > 79
                      ? 'match-rate-bg--high'
                      : item.matchRate > 49
                      ? 'match-rate-bg--medium'
                      : 'match-rate-bg--low',
                  ]"
                >
                  {{
                    item.matchRate > 79
                      ? '保'
                      : item.matchRate > 49
                      ? '稳'
                      : '冲'
                  }}
                </div>

                <span :class="item.matchRate ? 'num' : 'center-span'"
                  >{{ item.matchRate || '-'
                  }}<span class="question" v-if="item.matchRate">%</span></span
                >

                <div v-if="item.matchRate" class="risk">
                  {{
                    item.matchRate > 79
                      ? '较低风险'
                      : item.matchRate > 64
                      ? '中低风险'
                      : item.matchRate > 49
                      ? '中等风险'
                      : '较高风险'
                  }}
                </div>
              </div>
              <div class="second-column">
                <div class="school-info" @click="handleToSchoolDetail(item)">
                  <div class="top">
                    <img
                      :src="item.collegeInfo.icon"
                      class="school-avator"
                      alt=""
                    />
                    <div class="name">
                      {{ item.collegeInfo.name }} {{ item.groupName }}
                    </div>
                  </div>
                  <div class="middle">
                    {{ item.collegeInfo.dualClassName.replace(/,/g, ' / ') }}
                  </div>
                  <div class="bottom">
                    {{ item.collegeInfo.collegeType }}/{{
                      item.collegeInfo.natureName
                    }}<span>|</span>{{ item.collegeInfo.cityName
                    }}<span>|</span>院校招生代码：{{ item?.enrolCode || '-' }}
                  </div>
                </div>
              </div>
              <div class="third-column">
                <div class="offer-num">
                  <div class="num">
                    <span>{{ item.plannedNum }}</span
                    >人
                  </div>
                  <div class="subject">
                    {{ getSubjectShortName(item.limitSubject) }}
                  </div>
                </div>
              </div>
              <div class="fourth-column">
                <div
                  class="fourth-column-item"
                  v-for="(ele, ele_index) in thirdColumnLabelList"
                  :key="ele_index"
                >
                  {{ ele }}
                  <div
                    class="tooltip-wrapper"
                    v-if="ele == '最低分与省控线的差距'"
                  >
                    <img
                      v-if="ele == '最低分与省控线的差距'"
                      class="question-icon"
                      :src="questionLogo"
                      @click="showTooltip(1, item.cpgId)"
                    />
                    <div
                      class="tooltip-content"
                      v-if="tooltipStates[`${item.cpgId}-1`]"
                    >
                      专业组里的最低分与省控线差距大，录取概率相对较低。专业组里的最低分与省控线差距小，录取概率相对较高。
                    </div>
                  </div>
                  <div class="tooltip-wrapper" v-if="ele == '我的排名竞争力'">
                    <img
                      v-if="ele == '我的排名竞争力'"
                      class="question-icon"
                      :src="questionLogo"
                      @click="showTooltip(2, item.cpgId)"
                    />
                    <div
                      class="tooltip-content"
                      v-if="tooltipStates[`${item.cpgId}-2`]"
                    >
                      反映了考生当前成绩在当前院校的竞争力高低，等效位差只用于参考位次在历年竞争力情况，选择志愿时参考录取概率进行填报。
                    </div>
                  </div>
                </div>
              </div>
              <div class="fifth-column">
                <template v-if="item.previousData[0]">
                  <div class="fifth-column-item">
                    {{ item.previousData[0].admissionNum || '-' }}
                  </div>
                  <div class="fifth-column-item">
                    {{ item.previousData[0].lineDiffNum || '-' }}
                  </div>
                  <div class="fifth-column-item">
                    {{ item.previousData[0].minScore || '-' }}
                  </div>
                  <div class="fifth-column-item">
                    {{ item.previousData[0].minRank || '-' }}
                  </div>
                  <div class="fifth-column-item">
                    <span
                      :style="{
                        color:
                          item.previousData[0].competenceNum > 0
                            ? '#11B414'
                            : '#F76D32',
                      }"
                      >{{
                        item.previousData[0].competenceNum > 0
                          ? '高'
                          : item.previousData[0].competenceNum < 0
                          ? '低'
                          : ''
                      }}{{
                        item.previousData[0].competenceNum == null
                          ? '-'
                          : Math.abs(item.previousData[0].competenceNum) == 0 &&
                            item.previousData[0].competenceNum != null
                          ? '持平'
                          : Math.abs(item.previousData[0].competenceNum)
                      }}</span
                    >
                  </div>
                </template>
                <template v-else>
                  <div class="fifth-column-item no-data">-</div>
                </template>
              </div>
              <div class="sixth-column">
                <template v-if="item.previousData[1]">
                  <div class="sixth-column-item">
                    {{ item.previousData[1].admissionNum || '-' }}
                  </div>
                  <div class="sixth-column-item">
                    {{ item.previousData[1].lineDiffNum || '-' }}
                  </div>
                  <div class="sixth-column-item">
                    {{ item.previousData[1].minScore || '-' }}
                  </div>
                  <div class="sixth-column-item">
                    {{ item.previousData[1].minRank || '-' }}
                  </div>
                  <div class="sixth-column-item">
                    <span
                      :style="{
                        color:
                          item.previousData[1].competenceNum > 0
                            ? '#11B414'
                            : '#F76D32',
                      }"
                      >{{
                        item.previousData[1].competenceNum > 0
                          ? '高'
                          : item.previousData[1].competenceNum < 0
                          ? '低'
                          : ''
                      }}{{
                        item.previousData[1].competenceNum == null
                          ? '-'
                          : Math.abs(item.previousData[1].competenceNum) == 0 &&
                            item.previousData[1].competenceNum != null
                          ? '持平'
                          : Math.abs(item.previousData[1].competenceNum)
                      }}</span
                    >
                  </div>
                </template>
                <template v-else>
                  <div class="sixth-column-item no-data">-</div>
                </template>
              </div>
              <div class="seventh-column">
                <template v-if="item.previousData[2]">
                  <div class="seventh-column-item">
                    {{ item.previousData[2].admissionNum || '-' }}
                  </div>
                  <div class="seventh-column-item">
                    {{ item.previousData[2].lineDiffNum || '-' }}
                  </div>
                  <div class="seventh-column-item">
                    {{ item.previousData[2].minScore || '-' }}
                  </div>
                  <div class="seventh-column-item">
                    {{ item.previousData[2].minRank || '-' }}
                  </div>
                  <div class="seventh-column-item">
                    <span
                      :style="{
                        color:
                          item.previousData[2].competenceNum > 0
                            ? '#11B414'
                            : '#F76D32',
                      }"
                      >{{
                        item.previousData[2].competenceNum > 0
                          ? '高'
                          : item.previousData[2].competenceNum < 0
                          ? '低'
                          : ''
                      }}{{
                        item.previousData[2].competenceNum == null
                          ? '-'
                          : Math.abs(item.previousData[2].competenceNum) == 0 &&
                            item.previousData[2].competenceNum != null
                          ? '持平'
                          : Math.abs(item.previousData[2].competenceNum)
                      }}</span
                    >
                  </div>
                </template>
                <template v-else>
                  <div class="seventh-column-item no-data">-</div>
                </template>
              </div>
              <div class="eighth-column">
                <div
                  class="unfold-btn"
                  :class="{ 'unfold-btn-active': item.selectNum > 0 }"
                  @click="showPickMajorPopup(item)"
                >
                  {{ getParentBtnName(item) }}
                  <img
                    :src="item.selectNum > 0 ? downArrowWhite : blueArrowDown"
                    alt=""
                  />
                </div>
              </div>
            </div>
          </div>
        </template>
        <div v-if="isLoading" class="loading-text">加载中...</div>
        <div v-if="!hasMoreData && !isLoading" class="no-more">
          {{
            collegeName && schoolList.length == 0
              ? '在筛选范围内找不到该院校'
              : '没有更多数据了'
          }}
        </div>
      </div>
    </div>
    <transition name="slice">
      <div class="bottom-box" v-if="volunteerName">
        <div class="grade-info" @click="goToEdit">
          <img class="edit-icon" :src="editPen" alt="" />
          <span>{{ gradeInfo.provinceName }}</span>
          <div class="grey-column"></div>
          <span>{{ gradeInfo.subject }}</span>
          <div class="grey-column"></div>
          <span>{{ gradeInfo.score }}分</span>
          <div class="grey-column"></div>
          <span>{{ gradeInfo.rank }}位</span>
          <div class="grey-column"></div>
          <span>{{ gradeInfo.batchTypeName }}</span>
        </div>
        <div class="right-box" @click="checkMyVolunteerTable">
          <img :src="manageIcon" class="manage-icon" alt="" />
          {{ volunteerName }}
        </div>
        <div class="right-box plain" @click="checkOtherVolunteerTable">
          查看其他志愿表
        </div>
      </div>
    </transition>
  </div>
  <PickVolunteerMajorPopup
    v-model:visible="pickMajorDialogVisible"
    :currentCollegeItem="currentSelectCollege"
    :volunteerInfo="volunteerInfo"
    @updateCurrentCollege="updateCurrentCollege"
  />
</template>

<script setup>
import {
  reactive,
  ref,
  computed,
  onActivated,
  onDeactivated,
  watch,
  defineAsyncComponent,
  onUnmounted,
  nextTick,
} from 'vue';
import { showToast } from 'vant';
import { throttle, debounce } from 'lodash-es';
import { useRouter } from 'vue-router';
import { useVolunteerStore } from '@/store/volunteer';
import { useCollegeListCache } from '@/store/collegeListCache';
import arrowDown from '@/assets/images/arrowDown.png';
import editPen from '@/assets/images/editPen.png';
import manageIcon from '@/assets/images/manageIcon.png';
import blueArrowDown from '@/assets/images/blueArrowDown.png';
import downArrowWhite from '@/assets/images/downArrowWhite.png';
import { getSubjectShortName } from '@/utils/subjectData';
import {
  getProGroupList,
  getRushSteadyGroupNum,
  getVolunteerCurInfo,
} from '@/api/volunteer';
import { joinWithComma } from '@/utils/stringUtils';
const CollegeFeatureTypeDialog = defineAsyncComponent(() =>
  import(
    /* webpackChunkName: "college-feature-type-dialog" */ './CollegeFeatureTypeDialog.vue'
  )
);
const MajorDialog = defineAsyncComponent(() =>
  import(/* webpackChunkName: "major-dialog" */ './MajorDialog/index.vue')
);
const RecommendScoreDialog = defineAsyncComponent(() =>
  import(/* webpackChunkName: "major-dialog" */ './RecommendScoreDialog.vue')
);
const SearchCollege = defineAsyncComponent(() =>
  import(
    /* webpackChunkName: "search-college" */ './searchType/SearchCollege.vue'
  )
);
const PickVolunteerMajorPopup = defineAsyncComponent(() =>
  import(
    /* webpackChunkName: "pick-volunteer-major-popup" */ '@/components/PickVolunteerMajorPopup.vue'
  )
);

defineOptions({ name: 'CollegeList' });

const router = useRouter();
const store = useVolunteerStore();
const cacheStore = useCollegeListCache();

const volunteerInfo = computed(() => store.volunteerInfo);

const emit = defineEmits(['updateData']);

const props = defineProps({
  currentActiveTab: {
    type: Object,
    default: () => {},
  },
});

// 筛选条件
const filterList = reactive([
  {
    name: '院校',
    value: '院校',
  },
  {
    name: '专业',
    value: '专业',
  },
  {
    name: '推荐分数',
    value: '推荐分数',
  },
]);

const headerList = reactive([
  {
    label: '录取概率',
  },
  {
    label: '院校 - 专业组',
  },
  {
    label: '2024招生计划',
  },
  {
    label: '历年',
  },
  {
    label: '2024',
  },
  {
    label: '2023',
  },
  {
    label: '2022',
  },
  {
    label: '填报',
  },
]);

const thirdColumnLabelList = [
  '录取人数',
  '最低分与省控线的差距',
  '录取最低分',
  '录取最低位次',
  '我的排名竞争力',
];

const questionLogo =
  'https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/question.png';

// 分页
const pageNo = ref(1);
// 院校列表
const schoolList = ref([]);

const volunteerName = ref('');

const currentSchoolLevel = ref({});

const currentBatchType = computed(() => store.defaultBatchType); //BatchType

const batchTypeList = computed(() => store.batchTypeList);

// 生成缓存使用的基础 key（需要覆盖所有影响查询结果的条件）
const makeBaseKey = () => {
  const baseParams = {
    subject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    recordYear: volunteerInfo.value.defaultYear,
    userScore: volunteerInfo.value.score,
    rushSteadyState: props.currentActiveTab.key,
    userMinScore: currentScoreRange.value.min,
    userMaxScore: currentScoreRange.value.max,
    localRegionId: volunteerInfo.value.regionId,
    batchType: currentBatchType.value,
    collegeSearch: {
      regionIdList: currentProvinceCode,
      collegeType: currentCollegeType,
      dualClassName: currentSchoolFeatured,
      natureName: currentSchoolNature,
      levelName: currentCollegeLevel,
      matchName: collegeName.value,
    },
    professionSearch: {
      secondPositionTagNames: currentProfession,
      matchName: professionMatchName,
    },
    orderBy: '10',
  };
  return cacheStore.makeBaseKey(baseParams);
};

onActivated(() => {
  // currentSchoolLevel.value = batchTypeList.value.find(
  //   (item) => item.batchType == currentBatchType.value
  // );
  getVolunteerCurInfoFn();
  if (volunteerInfo.value?.relSubject) {
    getDefaultValue(volunteerInfo.value);
    debouncedGetData();
  }

  document.addEventListener('click', handleClickOutside);
  // 恢复滚动位置
  nextTick(() => {
    const el = scrollContainer.value;
    if (!el) return;
    el.scrollTop = cacheStore.getScrollTop(makeBaseKey());
  });
});

onDeactivated(() => {
  // 保存滚动位置
  const el = scrollContainer.value;
  if (el) {
    cacheStore.setScrollTop(makeBaseKey(), el.scrollTop);
  }
  document.removeEventListener('click', handleClickOutside);
});

const getVolunteerCurInfoFn = async () => {
  const params = {
    rankNum: volunteerInfo.value.position,
    subject: volunteerInfo.value.relSubject,
    score: volunteerInfo.value.score,
    regionId: volunteerInfo.value.regionId,
    batchType: currentBatchType.value,
  };
  const res = await getVolunteerCurInfo(params);
  if (res.code == 200) {
    volunteerName.value = res.data.title;
  }
};

let professionMatchName = '';

let currentProfession = '';

// 当前分数段
const currentScoreRange = ref({
  min: 0,
  max: 0,
});
const handleConfirmScoreRange = (newScoreRange) => {
  currentScoreRange.value.min = newScoreRange[0];
  currentScoreRange.value.max = newScoreRange[1];
  refreshAndGetData();
  showRecommendScoreDialog.value = false;
};

const currentScoreRangeName = ref('');

const refreshAndGetData = () => {
  pageNo.value = 1;
  schoolList.value = [];
  cacheStore.clearByBaseKeyPrefix(makeBaseKey());
  getProGroupListFn();
  getRushSteadyGroupNumFn();
};

const checkValid = (str) => {
  return !str || !/^(专业|院校|产业)/.test(str);
};

const goToEdit = () => {
  router.push({
    path: '/home',
    query: {
      from: 'vue',
    },
  });
};

const handleToSchoolDetail = (item) => {
  router.push({
    path: '/schoolDetail',
    query: {
      dataId: item.collegeId,
      dataName: item.collegeInfo.name,
    },
  });
};

const showCollegeDialog = ref(false);
const showMajorDialog = ref(false);
const showRecommendScoreDialog = ref(false);
const showDialog = (index) => {
  if (index == 0) {
    showCollegeDialog.value = !showCollegeDialog.value;
    showMajorDialog.value = false;
    showRecommendScoreDialog.value = false;
  } else if (index == 1) {
    showMajorDialog.value = !showMajorDialog.value;
    showRecommendScoreDialog.value = false;
    showCollegeDialog.value = false;
  } else if (index == 2) {
    showRecommendScoreDialog.value = !showRecommendScoreDialog.value;
    showCollegeDialog.value = false;
    showMajorDialog.value = false;
  } else if (index == 3) {
    showMajorDialog.value = false;
    showCollegeDialog.value = false;
    showRecommendScoreDialog.value = false;
  }
};

const currentSelectCollege = ref({});
const pickMajorDialogVisible = ref(false);
const showPickMajorPopup = (item) => {
  pickMajorDialogVisible.value = true;
  currentSelectCollege.value = item;
};

const updateCurrentCollege = (item) => {
  Object.assign(currentSelectCollege.value, item);
};

const createDefaultYearData = () => ({
  admissionNum: '', // 录取人数
  lineDiffNum: '', // 最低分与省控线的差距
  minScore: '', // 最低录取分数
  minRank: '', // 录取最低位次
  competenceNum: null, //我的排名竞争力
});

// 获取去年的年份
const getLastYear = () => {
  const currentDate = new Date();
  return currentDate.getFullYear() - 1;
};

headerList[2].label = `${volunteerInfo.value.planYear}招生计划`;
const defaultYear = volunteerInfo.value.defaultYear || getLastYear();
headerList[4].label = defaultYear;
headerList[5].label = defaultYear - 1;
headerList[6].label = defaultYear - 2;

let requestCount = 0;
const buildListParams = () => ({
  pageSize: 10,
  groupLevel: '1',
  subject: volunteerInfo.value.relSubject,
  searchAllowSubject: volunteerInfo.value.relSubject,
  subjectType: volunteerInfo.value.subjectType,
  recordYear: volunteerInfo.value.defaultYear,
  userScore: volunteerInfo.value.score,
  rushSteadyState: props.currentActiveTab.key,
  userMinScore: currentScoreRange.value.min,
  userMaxScore: currentScoreRange.value.max,
  localRegionId: volunteerInfo.value.regionId,
  batchType: currentBatchType.value,
  collegeSearch: {
    regionIdList: currentProvinceCode,
    collegeType: currentCollegeType,
    dualClassName: currentSchoolFeatured,
    natureName: currentSchoolNature,
    levelName: currentCollegeLevel,
    matchName: collegeName.value,
  },
  professionSearch: {
    secondPositionTagNames: currentProfession,
    matchName: professionMatchName,
  },
  orderBy: '10',
});
const getProGroupListFn = async () => {
  isLoading.value = true;
  const baseKey = makeBaseKey();
  const pageKey = cacheStore.makePageKey(baseKey, pageNo.value);
  // 读缓存
  const cached = cacheStore.getPage(pageKey);
  if (cached) {
    if (pageNo.value === 1) {
      schoolList.value = cached.list;
    } else {
      schoolList.value = [...schoolList.value, ...cached.list];
    }
    hasMoreData.value = cached.hasMore;
    isLoading.value = false;
    // SWR 静默刷新
    (async () => {
      try {
        const res = await getProGroupList({
          ...buildListParams(),
          pageNo: pageNo.value,
        });
        if (res.code === 200) {
          const validData = res.data.filter(
            (item) => item.collegeInfo && item.yearData
          );
          validData.forEach((item) => {
            item.showSonLevel = false;
            item.previousData = Array(3)
              .fill()
              .map(() => createDefaultYearData());
            if (item.yearData) {
              const firstYearData = item.yearData.find(
                (_item) => _item.year == defaultYear
              );
              item.previousData[0] = getYearData(firstYearData?.data);
              const secondYearData = item.yearData.find(
                (_item) => _item.year == defaultYear - 1
              );
              item.previousData[1] = getYearData(secondYearData?.data);
              const thirdYearData = item.yearData.find(
                (_item) => _item.year == defaultYear - 2
              );
              item.previousData[2] = getYearData(thirdYearData?.data);
            }
          });
          const hasMore = pageNo.value < res.pageparam.pages;
          cacheStore.setPage(pageKey, { list: validData, hasMore });
          if (pageNo.value === 1) {
            schoolList.value = validData;
          }
        }
      } catch (_) {}
    })();
    return;
  }
  const params = buildListParams();
  try {
    const res = await getProGroupList({
      ...params,
      pageNo: pageNo.value,
    });

    if (res.code === 200) {
      // 过滤有效数据并更新列表
      const validData = res.data.filter(
        (item) => item.collegeInfo && item.yearData
      );
      // 处理每个学校的历年数据
      validData.forEach((item) => {
        item.showSonLevel = false;
        item.previousData = Array(3)
          .fill()
          .map(() => createDefaultYearData());
        if (item.yearData) {
          const firstYearData = item.yearData.find(
            (_item) => _item.year == defaultYear
          );
          item.previousData[0] = getYearData(firstYearData?.data);
          const secondYearData = item.yearData.find(
            (_item) => _item.year == defaultYear - 1
          );
          item.previousData[1] = getYearData(secondYearData?.data);
          const thirdYearData = item.yearData.find(
            (_item) => _item.year == defaultYear - 2
          );
          item.previousData[2] = getYearData(thirdYearData?.data);
        }
      });

      schoolList.value =
        pageNo.value === 1 ? validData : [...schoolList.value, ...validData];

      const hasMore = pageNo.value < res.pageparam.pages;
      hasMoreData.value = hasMore;
      // 写缓存（按页）
      cacheStore.setPage(pageKey, { list: validData, hasMore });
      isLoading.value = false;
    } else {
      isLoading.value = false;
      schoolList.value = [];
      hasMoreData.value = false;
    }
  } catch (error) {
    schoolList.value = [];
    hasMoreData.value = false;
    isLoading.value = false;
    console.error('加载失败:', error);
    if (error.code === 'ERR_NETWORK') {
      if (requestCount < 3) {
        requestCount++;
        getProGroupListFn();
      } else {
        showToast('网络异常，请重新加载');
      }
    }
  }
};

let currentProvinceCode = '',
  currentProvinceName = '',
  currentCollegeType = '',
  currentSchoolFeatured = '',
  currentSchoolNature = '',
  currentCollegeLevel = '';
const handleConfirmCollege = (selectData) => {
  const {
    selectProvince,
    selectSchoolType,
    selectSchoolFeature,
    selectSchoolNature,
    selectSchoolLevel,
  } = selectData;
  currentProvinceCode = selectProvince.map((item) => item.code);
  currentProvinceName = selectProvince.map((item) => item.name).join(',');
  currentCollegeType = selectSchoolType.map((item) => item.code).join(',');
  currentSchoolFeatured = selectSchoolFeature
    .map((item) => item.code)
    .join(',');
  currentSchoolNature = selectSchoolNature.map((item) => item.code).join(',');
  currentCollegeLevel = selectSchoolLevel.map((item) => item.code).join(',');

  // 使用工具函数过滤空值并连接
  filterList[0].name =
    joinWithComma([
      currentProvinceName,
      currentCollegeType,
      currentSchoolFeatured,
      currentSchoolNature,
      currentCollegeLevel,
    ]) || '院校';
  refreshAndGetData();
  showCollegeDialog.value = false;
};

const handleConfirmMajor = (selectData) => {
  currentProfession = selectData.map((item) => item.name).join(',');
  filterList[1].name = currentProfession || '专业';
  refreshAndGetData();
  showMajorDialog.value = false;
};

const handleConfirmIndustry = (selectData) => {
  currentProfession = selectData;
  filterList[1].name = currentProfession || '专业';
  refreshAndGetData();
  showMajorDialog.value = false;
};

const keyList = [
  'admissionNum',
  'lineDiffNum',
  'minScore',
  'minRank',
  'competenceNum',
];
const getYearData = (data) => {
  if (!data) return null;
  const isNoData = keyList.every((key) => data[key] == null || data[key] == '');
  return isNoData ? null : data;
};

const getParentBtnName = (item) => {
  if (!item.volunteerNum) item.volunteerNum = 0;
  if (item.selectNum > 0) {
    return '志愿' + item.volunteerNum + '·' + '已选' + item.selectNum;
  } else {
    return '专业';
  }
};

const getRushSteadyGroupNumFn = async () => {
  const params = {
    groupLevel: '1',
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    recordYear: volunteerInfo.value.defaultYear,
    userScore: volunteerInfo.value.score,
    rushSteadyState: props.currentActiveTab.key,
    userMinScore: currentScoreRange.value.min,
    userMaxScore: currentScoreRange.value.max,
    localRegionId: volunteerInfo.value.regionId,
    batchType: currentBatchType.value,
    collegeSearch: {
      regionIdList: currentProvinceCode,
      collegeType: currentCollegeType,
      dualClassName: currentSchoolFeatured,
      natureName: currentSchoolNature,
      levelName: currentCollegeLevel,
      matchName: collegeName.value,
    },
    professionSearch: {
      secondPositionTagNames: currentProfession,
      matchName: professionMatchName,
    },
  };
  const res = await getRushSteadyGroupNum(params);
  if (res.code == 200) {
    emit('updateData', res.data); // 通知父组件更新四个数字
  }
};

// 带防抖的滚动处理
const handleScroll = throttle(
  (e) => {
    // 关闭所有弹窗
    closeAllTooltips();
    showCollegeDialog.value = false;
    showMajorDialog.value = false;

    // 如果正在加载或没有更多数据，直接返回
    if (isLoading.value || !hasMoreData.value) return;

    const container = e.target;
    const { scrollTop, clientHeight, scrollHeight } = container;

    // 当距离底部小于100px时触发加载
    const distanceToBottom = scrollHeight - (scrollTop + clientHeight);
    const loadTriggerDistance = 100;

    if (distanceToBottom <= loadTriggerDistance) {
      pageNo.value += 1;
      isLoading.value = true;
      getProGroupListFn();
    }
  },
  200,
  { leading: true, trailing: true }
); // 设置200ms的节流，同时启用首次和末次触发

// 标记是否正在加载（防止重复触发）
const isLoading = ref(false);
// 滚动容器引用
const scrollContainer = ref(null);
// 添加分页控制变量
const hasMoreData = ref(true);

const checkMyVolunteerTable = () => {
  router.push({
    path: '/volunTeerDetail',
  });
};

const checkOtherVolunteerTable = () => {
  router.push({
    path: '/myVolunteerTable',
    query: {
      fromType: 'vue',
    },
  });
};

const gradeInfo = reactive({
  provinceName: '广东',
  score: '500',
  rank: '10000',
  subject: '物化生',
});
const getDefaultValue = (newVal) => {
  gradeInfo.provinceName = newVal.regionName;
  gradeInfo.score = newVal.score;
  gradeInfo.rank = newVal.position;
  gradeInfo.batchTypeName = newVal.batchTypeName;
  gradeInfo.subject = newVal.subjectTypeDesc
    .split('、')
    .map((item) => item[0])
    .join('');
  currentScoreRange.value.min = Number(newVal.score) - 70;
  currentScoreRange.value.max = Number(newVal.score) + 30;
};
// 添加防抖的API调用函数
const debouncedGetData = debounce(() => {
  getProGroupListFn();
  getRushSteadyGroupNumFn();
}, 300);

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

watch(
  () => props.currentActiveTab,
  (newVal) => {
    pageNo.value = 1;
    schoolList.value = [];
    cacheStore.clearByBaseKeyPrefix(makeBaseKey());
    debouncedGetData();
  },
  { deep: true }
);

const collegeName = ref('');
const handleSelectCollege = (item) => {
  collegeName.value = item.name;
  refreshAndGetData();
};

const handleClear = (type) => {
  if (type == 'college') {
    collegeName.value = '';
  } else if (type == 'major') {
    professionMatchName = '';
  } else if (type == 'industry') {
    professionMatchName = '';
  }
  pageNo.value = 1;
  schoolList.value = [];
  cacheStore.clearByBaseKeyPrefix(makeBaseKey());
  getProGroupListFn();
  getRushSteadyGroupNumFn();
};

const tooltipStates = reactive({});
const closeAllTooltips = () => {
  Object.keys(tooltipStates).forEach((key) => {
    tooltipStates[key] = false;
  });
};

const handleClickOutside = (event) => {
  // 关闭 tooltip
  if (
    !event.target.closest('.tooltip-content') &&
    !event.target.closest('.question-icon')
  ) {
    closeAllTooltips();
  }

  // 关闭 CollegeFeatureTypeDialog 和 MajorDialog
  // 检查是否点击在需要排除的元素内
  const clickedElement = event.target;
  const isClickInFilterBox = clickedElement.closest('.filter-box-item');
  const isClickInCollegeDialog = clickedElement.closest('.college-dialog');
  const isClickInMajorDialog = clickedElement.closest('.major-dialog');
  const isClickInRecommendScoreDialog = clickedElement.closest('.score-dialog');

  // 如果点击在对话框内部或筛选框内部，则不关闭
  if (
    isClickInFilterBox ||
    isClickInCollegeDialog ||
    isClickInMajorDialog ||
    isClickInRecommendScoreDialog
  ) {
    return;
  }

  // 否则关闭对话框
  showCollegeDialog.value = false;
  showMajorDialog.value = false;
  showRecommendScoreDialog.value = false;
};

const showTooltip = (index, itemId) => {
  const key = `${itemId}-${index}`;
  tooltipStates[key] = !tooltipStates[key];
  // 关闭其他所有tooltip
  Object.keys(tooltipStates).forEach((k) => {
    if (k !== key) {
      tooltipStates[k] = false;
    }
  });
};

watch(
  currentScoreRange,
  (newVal) => {
    currentScoreRangeName.value = newVal.min + '-' + newVal.max;
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.gk-table {
  width: 100%;
  height: 100vh;
  background-color: #d4e6f9;
  display: flex;
  flex-direction: column;
  padding-bottom: 120px;
  box-sizing: border-box;
  position: relative;

  .filter-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 24px;
    padding: 18px 0;
    flex-shrink: 0;
    .filter-box-item {
      position: relative;
      background: #f7f8fa;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 20px;
      border-radius: 15px;
      width: 250px;
      .content {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24px;
        color: #000000;
        overflow: hidden;
      }
      .content-active {
        @extend .content;
        color: $primary-color;
        white-space: nowrap; /* 防止文本换行 */
        overflow: hidden; /* 隐藏超出部分 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
      .score-text {
        font-weight: 400;
        font-size: 24px;
        color: $primary-color;
        margin-left: 10px;
      }
      .arrow-down {
        width: 16px;
        height: 16px;
      }
    }
    .search-box {
      flex: 1;
      background-color: #f7f8fa;
      border-radius: 15px;
      position: relative;

      :deep(.van-search) {
        background-color: #f7f8fa;
        border-radius: 15px;
        padding: 6px 12px;

        .van-field__left-icon {
          font-size: 22px;
          color: #000;
        }

        .van-search__content {
          padding-left: 0;
          background-color: transparent;
        }

        .van-icon__image {
          width: 24px;
          height: 24px;
        }

        .van-field__control {
          font-size: 22px;
          color: #000;
        }
        .van-field__clear {
          font-size: 22px;
          color: #999;
        }

        .van-search__action {
          padding: 0 12px;
          color: $primary-color;
          font-size: 22px;
        }
      }
    }
  }

  .table-header {
    background: #f4f4f4;
    padding: 10px 0 12px 0;
    border-radius: 20px 20px 0 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    border-top: 1px solid #e3e3e3;
    .header-item {
      box-sizing: border-box;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 22px;
      color: #666666;
      flex: 0 0 auto;
      white-space: nowrap;
      &.item0 {
        width: 7%;
        text-align: center;
        padding: 0 0 0 0;
      }
      &.item1 {
        width: 38%;
        text-align: left;
        padding: 0 0 0 24px;
      }
      &.item2 {
        width: 8%;
        text-align: center;
        padding: 0 0 0 0;
      }
      &.item3 {
        width: 15%;
        text-align: right;
        padding: 0 24px 0 0;
      }
      &.item4 {
        width: 7%;
        text-align: left;
        padding: 0 0 0 16px;
      }
      &.item5 {
        width: 7%;
        text-align: left;
        padding: 0 0 0 16px;
      }
      &.item6 {
        width: 7%;
        text-align: left;
        padding: 0 0 0 16px;
      }
      &.item7 {
        // width: 7%;
        flex: 1;
        text-align: center;
        padding: 0 0 0 0;
      }
    }
  }

  .table-list {
    background-color: #fff;
    height: calc(100% - 42px); // 减去表头高度
    overflow-y: auto;
    padding-bottom: 180px;
    .table-item {
      margin-bottom: 20px;
      border-radius: 8px;
      border: 1px solid #dee8f4;
      &:last-child {
        margin-bottom: 0;
      }
      .father-level {
        background: #ffffff;
        box-shadow: 0px 9px 15px -9px #b8e7ff;
        border-radius: 8px;
        border-bottom: 1px solid #dee8f4;
        display: flex;
        .first-column {
          display: flex;
          flex-direction: column;
          width: 7%;
          box-sizing: border-box;
          border-right: 1px solid #e7e7e7;
          padding: 0 0 12px 28px;
          flex-shrink: 0;
          color: #222222;
          .num {
            font-weight: bold;
            font-size: 34px;
            color: #222222;
            margin: 17px 0 0 3px;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .center-span {
            margin-left: 20px;
            margin-top: 17px;
            font-weight: bold;
            font-size: 26px;
            color: #222222;
            margin-top: 50px;
          }
          .question {
            font-weight: bold;
            font-size: 22px;
            color: #222222;
            margin-left: 3px;
            font-family: D-DIN-PRO-600-SemiBold;
          }
          .label {
            width: 40px;
            height: 38px;
            color: #ffffff;
            font-size: 20px;
            font-weight: bold;
            display: flex;
            flex-direction: row;
            justify-content: center;
            padding-top: 6px;
          }
          .match-rate-bg {
            background-size: 100% 100%;
            background-repeat: no-repeat;
            background-position: center;

            &--high {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/green_bg.png);
            }

            &--medium {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/yellow_bg.png);
            }

            &--low {
              background-image: url(https://img3.job1001.com/ypMp/elan/images/career/collegeVolunteer/red_bg.png);
            }
          }
          .triangle-down {
            width: 0;
            height: 0;
            border-left: 13px solid transparent;
            border-right: 13px solid transparent;
            border-top: 12px solid transparent; /* 初始颜色为透明 */
            margin-bottom: 6px;
          }
          .risk {
            margin-top: 10px;
            font-weight: 400;
            font-size: 20px;
            color: #777777;
          }
        }
        .second-column {
          width: 38%;
          box-sizing: border-box;
          padding: 30px 24px;
          display: flex;
          justify-content: space-between;
          .school-info {
            .top {
              display: flex;
              flex-direction: row;
              align-items: center;
              gap: 8px;
              .school-avator {
                width: 28px;
                height: 30px;
                border-radius: 50%;
              }
              .name {
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 25px;
                color: #000000;
                cursor: pointer;
              }
            }
            .middle {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 22px;
              color: #777777;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              margin-top: 17px;
            }
            .bottom {
              display: flex;
              flex-wrap: nowrap;
              margin-top: 12px;
              font-family: PingFangSC, PingFang SC;
              font-size: 22px;
              color: #777777;
              span {
                margin: 0 13px;
              }
            }
          }
        }
        .third-column {
          width: 8%;
          box-sizing: border-box;
          padding: 34px 0 0 0;
          border-right: 1px solid #e7e7e7;
          .offer-num {
            display: flex;
            flex-direction: column;
            align-items: center;
            .num {
              span {
                font-family: D-DIN-PRO-600-SemiBold;
                font-size: 28px;
                color: #222222;
                font-weight: bold;
              }
              font-size: 18px;
            }
            .subject {
              font-weight: 400;
              font-size: 22px;
              color: #777777;
              margin-top: 16px;
            }
          }
        }
        .fourth-column {
          width: 15%;
          box-sizing: border-box;
          border-right: 1px solid #e7e7e7;
          padding: 4px 24px 4px 0px;
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          justify-content: center;
          color: #666;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 22px;
          .fourth-column-item {
            height: 32px;
            line-height: 32px;
            display: flex;
            flex-direction: row;
            align-items: center;
            img {
              width: 16px;
              height: 16px;
              margin-left: 2px;
              cursor: pointer;
            }
          }
        }
        .fifth-column,
        .sixth-column,
        .seventh-column {
          width: 7%;
          box-sizing: border-box;
          border-right: 1px solid #e7e7e7;
          padding: 0 0 0 16px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: flex-start;
          color: #222222;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 20px;
          .sixth-column-item,
          .seventh-column-item,
          .fifth-column-item {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            height: 30px;
            line-height: 30px;
            img {
              width: 12px;
              height: 12px;
            }
          }
          .no-data {
            color: #999999;
          }
        }
        .eighth-column {
          flex: 1;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: center;
          .unfold-btn {
            padding: 9px 12px;
            background: #eef5ff;
            border-radius: 4px;
            border: 1px solid $primary-color;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 22px;
            color: $primary-color;
            cursor: pointer;
            img {
              width: 16px;
              height: 16px;
              margin-left: 8px;
            }
          }
          .unfold-btn-active {
            padding: 9px 12px;
            font-size: 22px;
            background: $primary-color;
            color: #fff;
          }
        }
      }
    }
  }

  .table-contain {
    flex: 1;
    min-height: 0;
    border-radius: 20px;
    display: flex;
    flex-direction: column;
    background: #fff;
  }

  .table-header {
    flex-shrink: 0;
  }

  .table-list {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    background-color: #fff;
  }

  .loading-text,
  .no-more {
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 20px;
    color: #999;
  }

  .bottom-box {
    width: 100%;
    position: fixed;
    bottom: 0;
    background: #ebf5ff;
    padding: 16px 32px;
    margin: 0 -32px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .box-item {
      padding: 13px 20px;
      background: #f7f8fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: 400;
      font-size: 22px;
      color: #000000;
      position: relative;
      box-sizing: border-box;
      margin-right: 16px;
      .arrow-down {
        margin-left: 16px;
        width: 14px;
        height: 14px;
      }
    }
    .grade-info {
      display: flex;
      flex-direction: row;
      align-items: center;
      display: flex;
      flex-direction: row;
      align-items: center;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24px;
      color: #3967aa;
      margin-right: 16px;
      .edit-icon {
        width: 20px;
        height: 20px;
        margin-right: 14px;
      }
      .grey-column {
        width: 1px;
        height: 10px;
        background: #3967aa;
        margin: 4px 10px 0 10px;
      }
    }
    .right-box {
      background: $primary-color;
      border-radius: 6px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 24px;
      padding: 16px 32px;
      color: #ffffff;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      .manage-icon {
        width: 24px;
        height: 24px;
        margin-right: 12px;
      }
      &.plain {
        margin-left: 16px;
        background: #ebf5ff;
        color: $primary-color;
        border: 1px solid $primary-color;
      }
    }
  }
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s ease-in;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}

.slice-enter-active,
.slice-leave-active {
  transition: all 0.3s ease;
}

.slice-enter-from,
.slice-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

.tooltip-wrapper {
  position: relative;
  .question-icon {
    width: 14px;
    height: 14px;
    margin-left: 2px;
    cursor: pointer;
  }
  .tooltip-content {
    font-size: 22px;
    width: 220px;
    padding: 12px 24px;
    position: absolute;
    top: 18px;
    left: 18px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    z-index: 1000;
    color: #333;
  }
}
</style>
